import React, { Component } from 'react';
import { connect } from 'dva';

import { Form, Col, Row, message, Cascader, Empty } from 'antd';
import { UmiComponentProps, FormComponentProps } from '@/common/type';

import { Viewer } from '@/components/PointSelect';
import { BASE_URL } from '@/config/query';
import request from '@/utils/request';
import empty from '@/assets/images/empty.png';

interface P {
  data?: {
    id?: string;
    buildId?: string; floorId?: string; areaId?: string;
  },
  location?: Array<any>;
  lLocation?: boolean;
}
type Props = P & UmiComponentProps & FormComponentProps;

@connect(({ position_xl, loading }) => ({
  dict: position_xl.dict || {},
  location: position_xl.location || [],
  type: position_xl.type || [],
  image: position_xl.image,
  lLocation: loading.effects['position_xl/queryLocation'],
  lType: loading.effects['position_xl/queryType'],
}))
class FormItem extends Component<Props, any> {
  state = {
    url: null,
    points: null
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({
      type: 'position_xl/init', payload: {
        dict: { keyList: {} },
      }
    })
    if (data) {
      const {
        buildId, floorId, areaId,
        ...res
      } = data;

      form.setFieldsValue({
        ...res
      })
    }
  }

  handleMap = () => {
    const { form, data } = this.props;
    const { getFieldValue } = form;

    const list = getFieldValue('buildList');
    if ((!Array.isArray(list) || !list[1]) && !data.floorId) {
      message.warn('请选择楼层');
      return;
    }
  }


  loadData = async (type, selectedOptions) => {
    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    dispatch({
      type: `position_xl/${type}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  onChange = async (value, selectedOptions) => {
    if (value.length === 2) {
      const targetOption = value[value.length - 1];
      const [floor, points] = await Promise.all([
        request(`${BASE_URL}/floor_plan/detail/${targetOption.split('%%')[0]}`),
        request(`${BASE_URL}/position/list`, { floor: targetOption.split('%%')[0] })
      ])

      this.setState({
        url: floor.floorPlan,
        points: Array.isArray(points) ? points.map(v => ({
          left: v.x,
          top: v.y,
          show: true,
          id: v.id
        })).filter(u => u.left) : []
      })
    }
  }

  render() {
    const { form, data } = this.props;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 16 },
      },
    };

    return (
      <section>
        <Form>
          <Row style={{ minHeight: '75vh' }}>
            <Col span={12}>
              <Form.Item
                {...formItemLayout}
                label='所在位置'
                required
              >
                {getFieldDecorator('buildList')(
                  <Cascader
                    // disabled={!!(data && data.id)}
                    options={this.props.location}
                    loadData={this.loadData.bind(this, 'queryLocation')}
                    changeOnSelect
                    onChange={this.onChange}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={12}></Col>
            <Col span={24}>
              {
                this.state.url
                  ? <Viewer image={this.state.url} points={this.state.points} />
                  : <Empty
                      image={empty}
                      description={
                        <span style={{ color: 'rgba(0, 0, 0, 0.75)' }}>暂无数据</span>
                      }
                      imageStyle={{
                        height: '50%',
                      }}
                    />
              }
            </Col>
          </Row>
        </Form >
      </section>
    );
  }
}

const FormList = Form.create<Props>()(FormItem);
export default FormList;